package com.ruoyi.binance.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binance.api.OrderApi;
import com.ruoyi.binance.domain.*;
import com.ruoyi.binance.mapper.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

@Component
public class AsyncAPriceMonitoring {

    @Autowired
    private BinanceMinKMapper stockMinKMapper;
    @Autowired
    private BinanceMinAverageMapper binanceMinAverageMapper;
    @Autowired
    private BinanceAPriceMonitoringMapper binanceAPriceMonitoringMapper;
    @Autowired
    private BinanceTransactionOrderMapper binanceTransactionOrderMapper;
    @Autowired
    private BinanceTransactionConfMapper binanceTransactionConfMapper;
    @Autowired
    private Binance15minAverageMapper binance15minAverageMapper;
    @Autowired
    private Binance30minAverageMapper binance30minAverageMapper;
    @Autowired
    private BinanceHourAverageMapper binanceHourAverageMapper;
    @Autowired
    private Binance15minDayAveMapper binance15minDayAveMapper;

    @Async
    public void getAPriceMonitoring(Long confId, String code, Date time, BigDecimal close, BigDecimal open) {

        BinanceAPriceMonitoring aPriceMonitoring = binanceAPriceMonitoringMapper.selectBinanceAPriceMonitoringByCode(code);
        if (aPriceMonitoring == null) {
            return;
        }
        //根据监控均价类型赋值均价
        BinanceMinAverage binanceMinAverage = binanceMinAverageMapper.selectBinanceMinAverageByCodeAndTime(code, DateUtils.getFormatTime(time));
        BigDecimal averagePriceDay = binanceMinAverage.getPrice();
        BigDecimal averagePrice = close;
        if ("DAY".equals(aPriceMonitoring.getAvgType())) {
            averagePrice = averagePriceDay;
        }
        if ("HOUR".equals(aPriceMonitoring.getAvgType())) {
            BinanceHourAverage binanceHourAverage = binanceHourAverageMapper.selectBinanceHourAverageByCodeAndTime(code, DateUtils.getFormatTime(time));
            averagePrice = binanceHourAverage.getPrice();
        }
        if ("MIN30".equals(aPriceMonitoring.getAvgType())) {
            Binance30minAverage binance30minAverage = binance30minAverageMapper.selectBinance30minAverageByCodeAndTime(code, DateUtils.getFormatTime(time));
            averagePrice = binance30minAverage.getPrice();
        }
        if ("MIN15".equals(aPriceMonitoring.getAvgType())) {
            Binance15minAverage binance15minAverage = binance15minAverageMapper.selectBinance15minAverageByCodeAndTime(code, DateUtils.getFormatTime(time));
            averagePrice = binance15minAverage.getPrice();
        }
        if("MIN15_DAY".equals(aPriceMonitoring.getAvgType())){
            Binance15minDayAve binance15minDayAve = binance15minDayAveMapper.selectBinance15minDayAveByCodeAndTime(code, DateUtils.getFormatTime(time));
            averagePrice = binance15minDayAve.getPrice();
        }

        //获取上一分钟的收盘价
        BigDecimal lastClose = open;
        BinanceMinK minK = stockMinKMapper.selectBinanceMinKByCodeAndTime(code, DateUtils.getFormatTime(DateUtils.addMinutes(time, -1)));
        if (minK != null && minK.getClose() != null) {
            lastClose = minK.getClose();
        }
        //收盘价小于等于均价
        if (close.compareTo(averagePrice) <= 0) {
            //进行下单 卖出
            BinanceTransactionConf binanceTransactionConf = binanceTransactionConfMapper.selectBinanceTransactionConfById(confId);
            if (binanceTransactionConf != null && binanceTransactionConf.getCoinNumber().compareTo(BigDecimal.ZERO) > 0
                    && !"SELL".equals(binanceTransactionConf.getSide()) && lastClose.compareTo(close) > 0) {
                BinanceTransactionConf bean = new BinanceTransactionConf();
                bean.setId(binanceTransactionConf.getId());
                bean.setSide("SELL");
                binanceTransactionConfMapper.updateBinanceTransactionConf(bean);

                BinanceTransactionOrder order = new BinanceTransactionOrder();
                order.setCode(code);
                order.setOrgOrderId(IdUtil.getSnowflakeNextIdStr());
                order.setQuantity(binanceTransactionConf.getCoinNumber());
                order.setSide("SELL");
                order.setType("MARKET");
                order.setConfigId(confId);
                order.setCreateTime(time);
                order.setRemark("自动交易");
                int save = binanceTransactionOrderMapper.insertBinanceTransactionOrder(order);
                if (save > 0) {
                    //调用下单接口
                    JSONObject res = OrderApi.order(order);
                    if (StringUtils.isNotBlank(res.getString("code"))) {
                        order.setStatus("REJECTED");
                        order.setRemark(res.getString("msg"));

                        bean.setSide("BUY");
                        binanceTransactionConfMapper.updateBinanceTransactionConf(bean);
                    } else {
                        order.setStatus("PENDING_NEW");
                        order.setOrderId(res.getString("orderId"));
                    }
                    binanceTransactionOrderMapper.updateBinanceTransactionOrder(order);
                }
            }
        }
        //收盘价大于等于均价
        if (close.compareTo(averagePrice) >= 0) {
            //进行下单 买入
            BinanceTransactionConf binanceTransactionConf = binanceTransactionConfMapper.selectBinanceTransactionConfById(confId);
            if (binanceTransactionConf != null && binanceTransactionConf.getUsdtNumber().compareTo(BigDecimal.ZERO) > 0
                    && !"BUY".equals(binanceTransactionConf.getSide()) && lastClose.compareTo(close) < 0) {
                BinanceTransactionConf bean = new BinanceTransactionConf();
                bean.setId(binanceTransactionConf.getId());
                bean.setSide("BUY");
                binanceTransactionConfMapper.updateBinanceTransactionConf(bean);

                BinanceTransactionOrder order = new BinanceTransactionOrder();
                order.setCode(code);
                order.setOrgOrderId(IdUtil.getSnowflakeNextIdStr());
                order.setQuoteOrderQty(binanceTransactionConf.getUsdtNumber());
                order.setSide("BUY");
                order.setType("MARKET");
                order.setConfigId(confId);
                order.setCreateTime(time);
                order.setRemark("自动交易");
                int save = binanceTransactionOrderMapper.insertBinanceTransactionOrder(order);
                if (save > 0) {
                    //调用下单接口
                    JSONObject res = OrderApi.order(order);
                    if (StringUtils.isNotBlank(res.getString("code"))) {
                        order.setStatus("REJECTED");
                        order.setRemark(res.getString("msg"));

                        bean.setSide("SELL");
                        binanceTransactionConfMapper.updateBinanceTransactionConf(bean);
                    } else {
                        order.setStatus("PENDING_NEW");
                        order.setOrderId(res.getString("orderId"));
                    }
                    binanceTransactionOrderMapper.updateBinanceTransactionOrder(order);
                }
            }
        }
    }
}
